const db = require('../config/db');
const { getCarousels, createCarousel, updateCarousel, deleteCarousel } = require('../models/Carousel');
const { getHotStores, addHotStore, updateHotStore, removeHotStore } = require('../models/Store');
const jwt = require('jsonwebtoken');

// 用于存储验证码的Map，key为手机号，value为{code: string, timestamp: number}
const verificationCodes = new Map();

// 生成6位随机验证码
const generateVerificationCode = () => {
  return Math.floor(100000 + Math.random() * 900000).toString();
};

// 发送验证码
const sendVerificationCode = async (req, res) => {
  try {
    const { phone } = req.body;

    // 验证手机号格式
    if (!phone || !/^1[3-9]\d{9}$/.test(phone)) {
      return res.status(400).json({ message: '无效的手机号码' });
    }

    // 检查是否是管理员手机号
    const [admins] = await db.query(
      'SELECT id FROM users WHERE phone = ? AND role IN ("super", "store")',
      [phone]
    );

    if (admins.length === 0) {
      return res.status(403).json({ message: '该手机号不是管理员账号' });
    }

    // 检查是否在60秒内重复发送
    const existingCode = verificationCodes.get(phone);
    if (existingCode && (Date.now() - existingCode.timestamp) < 60000) {
      return res.status(429).json({ message: '请等待60秒后再次获取验证码' });
    }

    // 生成新的验证码
    const code = generateVerificationCode();
    
    // 存储验证码（实际项目中应该使用Redis）
    verificationCodes.set(phone, {
      code,
      timestamp: Date.now()
    });

    // TODO: 实际项目中这里应该调用短信服务发送验证码
    console.log(`向手机号 ${phone} 发送验证码: ${code}`);

    res.json({ 
      success: true,
      message: '验证码已发送',
      // 开发环境直接返回验证码，生产环境需要移除
      code: process.env.NODE_ENV === 'development' ? code : undefined
    });

  } catch (error) {
    console.error('发送验证码失败:', error);
    res.status(500).json({ message: '发送验证码失败' });
  }
};

// 验证验证码
const verifyCode = (phone, code) => {
  const storedData = verificationCodes.get(phone);
  
  if (!storedData) {
    return false;
  }

  // 验证码5分钟内有效
  if (Date.now() - storedData.timestamp > 300000) {
    verificationCodes.delete(phone);
    return false;
  }

  if (storedData.code !== code) {
    return false;
  }

  // 验证成功后删除验证码
  verificationCodes.delete(phone);
  return true;
};

// 轮播图管理
const getAllCarousels = async (req, res) => {
    console.log('[ADMIN] 获取所有轮播图列表');
    try {
        const carousels = await getCarousels();
        console.log('[ADMIN] 轮播图列表获取成功', { count: carousels.length });
        res.json(carousels);
    } catch (error) {
        console.error('[ADMIN] 获取轮播图失败', { error: error.message });
        res.status(500).json({ message: '获取轮播图失败' });
    }
};

const createNewCarousel = async (req, res) => {
    console.log('[ADMIN] 创建新轮播图', { data: req.body });
    try {
        const result = await createCarousel(req.body);
        console.log('[ADMIN] 轮播图创建成功', { carouselId: result.insertId });
        res.status(201).json({ message: '轮播图创建成功', id: result.insertId });
    } catch (error) {
        console.error('[ADMIN] 轮播图创建失败', { error: error.message, data: req.body });
        res.status(500).json({ message: '创建轮播图失败' });
    }
};

const modifyCarousel = async (req, res) => {
    console.log('[ADMIN] 更新轮播图', { carouselId: req.params.id, data: req.body });
    try {
        await updateCarousel(req.params.id, req.body);
        console.log('[ADMIN] 轮播图更新成功', { carouselId: req.params.id });
        res.json({ message: '轮播图更新成功' });
    } catch (error) {
        console.error('[ADMIN] 轮播图更新失败', { carouselId: req.params.id, error: error.message });
        res.status(500).json({ message: '更新轮播图失败' });
    }
};

const removeCarousel = async (req, res) => {
    console.log('[ADMIN] 删除轮播图', { carouselId: req.params.id });
    try {
        await deleteCarousel(req.params.id);
        console.log('[ADMIN] 轮播图删除成功', { carouselId: req.params.id });
        res.json({ message: '轮播图删除成功' });
    } catch (error) {
        console.error('[ADMIN] 轮播图删除失败', { carouselId: req.params.id, error: error.message });
        res.status(500).json({ message: '删除轮播图失败' });
    }
};

// 热点推荐管理
const getHotStoresList = async (req, res) => {
    console.log('[ADMIN] 获取热点店铺列表');
    try {
        const stores = await getHotStores();
        console.log('[ADMIN] 热点店铺列表获取成功', { count: stores.length });
        res.json(stores);
    } catch (error) {
        console.error('[ADMIN] 获取热点店铺失败', { error: error.message });
        res.status(500).json({ message: '获取热点店铺失败' });
    }
};

const addNewHotStore = async (req, res) => {
    console.log('[ADMIN] 添加热点店铺', { data: req.body });
    try {
        const { title, description, imageUrl, linkUrl, sortOrder = 0, status = 'active' } = req.body;
        
        // 验证必填字段
        if (!title || !imageUrl) {
            return res.status(400).json({ message: '标题和图片不能为空' });
        }

        // 构建数据对象
        const hotStoreData = {
            title,
            description: description || '',
            image_url: imageUrl,
            link_url: linkUrl || '',
            sort_order: sortOrder,
            status
        };

        // 添加到数据库
        const result = await db.execute(
            `INSERT INTO hot_recommends 
            (title, description, image_url, link_url, sort_order, status) 
            VALUES (?, ?, ?, ?, ?, ?)`,
            [
                hotStoreData.title,
                hotStoreData.description,
                hotStoreData.image_url,
                hotStoreData.link_url,
                hotStoreData.sort_order,
                hotStoreData.status
            ]
        );

        console.log('[ADMIN] 热点店铺添加成功', { id: result.insertId });
        res.status(201).json({ 
            message: '添加热点店铺成功',
            data: {
                id: result.insertId,
                ...hotStoreData
            }
        });
    } catch (error) {
        console.error('[ADMIN] 热点店铺添加失败', { error: error.message });
        res.status(500).json({ message: '添加热点店铺失败' });
    }
};

const modifyHotStore = async (req, res) => {
    console.log('[ADMIN] 更新热点店铺', { id: req.params.id, data: req.body });
    try {
        const { title, description, imageUrl, linkUrl, sortOrder, status } = req.body;
        const id = req.params.id;

        // 验证必填字段
        if (!title || !imageUrl) {
            return res.status(400).json({ message: '标题和图片不能为空' });
        }

        // 构建更新SQL
        const sql = `
            UPDATE hot_recommends 
            SET title = ?, 
                description = ?, 
                image_url = ?, 
                link_url = ?, 
                sort_order = ?, 
                status = ?
            WHERE id = ?
        `;

        await db.execute(sql, [
            title,
            description || '',
            imageUrl,
            linkUrl || '',
            sortOrder || 0,
            status || 'active',
            id
        ]);

        console.log('[ADMIN] 热点店铺更新成功', { id });
        res.json({ 
            message: '热点店铺更新成功',
            data: {
                id,
                title,
                description,
                imageUrl,
                linkUrl,
                sortOrder,
                status
            }
        });
    } catch (error) {
        console.error('[ADMIN] 热点店铺更新失败', { id: req.params.id, error: error.message });
        res.status(500).json({ message: '热点店铺更新失败' });
    }
};

const deleteHotStore = async (req, res) => {
    console.log('[ADMIN] 删除热点店铺', { hotStoreId: req.params.id });
    try {
        await removeHotStore(req.params.id);
        console.log('[ADMIN] 热点店铺删除成功', { hotStoreId: req.params.id });
        res.json({ message: '热点店铺删除成功' });
    } catch (error) {
        console.error('[ADMIN] 热点店铺删除失败', { hotStoreId: req.params.id, error: error.message });
        res.status(500).json({ message: '热点店铺删除失败' });
    }
};

// 店铺管理接口
const getStoresList = async (req, res) => {
    console.log('[ADMIN] 获取店铺列表', { query: req.query, params: req.params });
    try {
        // 解析前端可能以params字符串形式传递的参数
        let status = req.query.status;
        let page = req.query.page || 1;
        let limit = req.query.limit || 10;
        
        // 检查是否有params参数（前端可能将参数放在params字段中）
        if (req.query.params) {
            try {
                const paramsObj = JSON.parse(req.query.params);
                status = paramsObj.status || status;
                page = paramsObj.page || page;
                limit = paramsObj.limit || limit;
            } catch (e) {
                console.error('[ADMIN] 解析params参数失败:', e.message);
            }
        }
        
        // 确保参数是数字类型
        const pageNum = parseInt(page) || 1;
        const limitNum = parseInt(limit) || 10;
        
        console.log('[ADMIN] 查询参数:', { page: pageNum, limit: limitNum, status });
        
        // 获取商家申请列表
        const result = await require('../models/Store').getMerchantApplications({
            status,
            page: pageNum,
            limit: limitNum
        });
        
        console.log('[ADMIN] 店铺列表获取成功', { 
            count: result.list.length, 
            total: result.total,
            page: result.page,
            limit: result.limit
        });
        
        res.json({
            code: 200,
            data: result
        });
    } catch (error) {
        console.error('[ADMIN] 获取店铺列表失败', { 
            error: error.message,
            stack: error.stack 
        });
        res.status(500).json({ 
            code: 500, 
            message: '获取店铺列表失败',
            error: error.message
        });
    }
};

const getStoreDetail = async (req, res) => {
    console.log('[ADMIN] 获取店铺详情', { applicationId: req.params.id });
    try {
        // 获取商家申请详情
        const applicationDetail = await require('../models/Store').getMerchantApplicationDetail(req.params.id);
        
        console.log('[ADMIN] 店铺详情获取成功', { applicationId: req.params.id });
        res.json({
            code: 200,
            data: applicationDetail
        });
    } catch (error) {
        console.error('[ADMIN] 获取店铺详情失败', { applicationId: req.params.id, error: error.message });
        res.status(error.message === '商家申请不存在' ? 404 : 500).json({ 
            code: error.message === '商家申请不存在' ? 404 : 500, 
            message: error.message || '获取店铺详情失败' 
        });
    }
};

const auditStore = async (req, res) => {
    console.log('[ADMIN] 审核店铺', { applicationId: req.params.id, data: req.body });
    try {
        const { status, rejectReason } = req.body;
        
        // 验证参数
        if (!status || !['approved', 'rejected'].includes(status)) {
            return res.status(400).json({ code: 400, message: '无效的审核状态' });
        }
        
        // 如果拒绝，需要提供拒绝原因
        if (status === 'rejected' && !rejectReason) {
            return res.status(400).json({ code: 400, message: '拒绝时需要提供拒绝原因' });
        }
        
        // 执行审核
        await require('../models/Store').auditMerchantApplication(req.params.id, { 
            status, 
            rejectReason 
        });
        
        console.log('[ADMIN] 店铺审核成功', { applicationId: req.params.id, status });
        res.json({ 
            code: 200, 
            message: status === 'approved' ? '店铺审核通过' : '店铺审核已拒绝' 
        });
    } catch (error) {
        console.error('[ADMIN] 审核店铺失败', { applicationId: req.params.id, error: error.message });
        res.status(error.message === '商家申请不存在' ? 404 : 500).json({ 
            code: error.message === '商家申请不存在' ? 404 : 500, 
            message: error.message || '店铺审核失败' 
        });
    }
};

// 优惠券管理接口
const getCouponsList = async (req, res) => {
    console.log('[ADMIN] 获取优惠券列表');
    try {
        // 实际实现需根据数据库结构调整
        res.json([]);
    } catch (error) {
        console.error('[ADMIN] 获取优惠券列表失败', { error: error.message });
        res.status(500).json({ message: '获取优惠券列表失败' });
    }
};

const createCoupon = async (req, res) => {
    console.log('[ADMIN] 创建优惠券', { data: req.body });
    try {
        // 实际实现需根据数据库结构调整
        res.status(201).json({ message: '优惠券创建成功' });
    } catch (error) {
        console.error('[ADMIN] 创建优惠券失败', { error: error.message });
        res.status(500).json({ message: '创建优惠券失败' });
    }
};

const updateCouponStatus = async (req, res) => {
    console.log('[ADMIN] 更新优惠券状态', { couponId: req.params.id, data: req.body });
    try {
        // 实际实现需根据数据库结构调整
        res.json({ message: '优惠券状态更新成功' });
    } catch (error) {
        console.error('[ADMIN] 更新优惠券状态失败', { couponId: req.params.id, error: error.message });
        res.status(500).json({ message: '更新优惠券状态失败' });
    }
};

// 数据统计接口
const getUsersStats = async (req, res) => {
    console.log('[ADMIN] 获取用户统计数据');
    try {
        // 实际实现需根据数据库结构调整
        const [rows] = await db.execute('SELECT COUNT(*) as total, DATE(created_at) as date FROM users GROUP BY date');
        console.log('[ADMIN] 用户统计数据获取成功', { recordCount: rows.length });
        console.log('[ADMIN] 优惠券统计数据获取成功', { recordCount: rows.length });
        console.log('[ADMIN] 加油站流水统计数据获取成功', { recordCount: rows.length });
        res.json(rows);
    } catch (error) {
        console.error('[ADMIN] 用户统计数据获取失败', { error: error.message });
        res.status(500).json({ message: '获取用户统计失败' });
    }
};

const getCouponsStats = async (req, res) => {
    console.log('[ADMIN] 获取优惠券统计数据');
    try {
        // 实际实现需根据数据库结构调整
        const [rows] = await db.execute('SELECT COUNT(*) as total, used FROM coupons GROUP BY used');
        res.json(rows);
    } catch (error) {
        console.error('[ADMIN] 优惠券统计数据获取失败', { error: error.message });
        res.status(500).json({ message: '获取优惠券统计失败' });
    }
};

const getStatistics = async (req, res) => {
    console.log('[ADMIN] 获取数据统计');
    try {
        // 获取日期范围参数
        const { start_date, end_date } = req.query;
        console.log('[ADMIN] 统计日期范围:', { start_date, end_date });

        // TODO: 实际项目中需要根据日期范围查询数据库
        // 这里返回模拟数据用于前端开发
        res.json({
            userStats: {
                total: 1000,
                new: 50,
                newRate: 5.0
            },
            couponStats: {
                total: 500,
                used: 300,
                usedRate: 60.0
            },
            transactionStats: {
                total: 50000,
                count: 1000
            },
            transactions: [
                {
                    id: 1,
                    create_time: '2024-01-05 10:00:00',
                    station_name: '示例加油站1',
                    amount: 100,
                    status: 'success'
                },
                {
                    id: 2,
                    create_time: '2024-01-05 11:00:00',
                    station_name: '示例加油站2',
                    amount: 200,
                    status: 'success'
                }
            ],
            userChartData: {
                dates: ['2024-01-01', '2024-01-02', '2024-01-03', '2024-01-04', '2024-01-05'],
                values: [900, 920, 950, 980, 1000]
            },
            couponChartData: {
                dates: ['2024-01-01', '2024-01-02', '2024-01-03', '2024-01-04', '2024-01-05'],
                values: [100, 150, 200, 250, 300]
            },
            transactionChartData: {
                dates: ['2024-01-01', '2024-01-02', '2024-01-03', '2024-01-04', '2024-01-05'],
                values: [10000, 20000, 30000, 40000, 50000]
            }
        });
    } catch (error) {
        console.error('[ADMIN] 数据统计失败', { error: error.message });
        res.status(500).json({ message: '获取统计数据失败' });
    }
};

const logout = async (req, res) => {
    console.log('[ADMIN] 管理员登出');
    try {
        // 清除会话或令牌
        res.json({ message: '登出成功' });
    } catch (error) {
        console.error('[ADMIN] 登出失败', { error: error.message });
        res.status(500).json({ message: '登出失败' });
    }
};

const getAdminInfo = async (req, res) => {
    console.log('[ADMIN] 获取管理员信息');
    try {
        // 实际实现需根据数据库结构调整
        const adminInfo = {
            id: req.user.id,
            username: req.user.username,
            role: req.user.role
        };
        res.json(adminInfo);
    } catch (error) {
        console.error('[ADMIN] 获取管理员信息失败', { error: error.message });
        res.status(500).json({ message: '获取管理员信息失败' });
    }
};

const getGasStationsStats = async (req, res) => {
    console.log('[ADMIN] 获取加油站流水统计数据');
    try {
        // 实际实现需根据数据库结构调整
        const [rows] = await db.execute('SELECT SUM(amount) as total, DATE(transaction_time) as date FROM gas_transactions GROUP BY date');
        res.json(rows);
    } catch (error) {
        console.error('[ADMIN] 加油站流水统计数据获取失败', { error: error.message });
        res.status(500).json({ message: '获取加油站流水统计失败' });
    }
};

// 登录处理
const login = async (req, res) => {
  try {
    const { phone, code } = req.body;

    // 验证手机号格式
    if (!phone || !/^1[3-9]\d{9}$/.test(phone)) {
      return res.status(400).json({ message: '无效的手机号码' });
    }

    // 验证验证码
    if (!code || !verifyCode(phone, code)) {
      return res.status(400).json({ message: '验证码无效或已过期' });
    }

    // 查询管理员信息
    const [admins] = await db.execute(
      'SELECT id, name, role, phone FROM users WHERE phone = ? AND role IN ("super", "store")',
      [phone]
    );

    if (admins.length === 0) {
      return res.status(403).json({ message: '该手机号不是管理员账号' });
    }

    const admin = admins[0];
    console.log('查询到的管理员信息:', admin);

    // 生成JWT token，24小时有效
    const token = jwt.sign(
      { 
        id: admin.id,
        role: admin.role,
        phone: admin.phone
      },
      process.env.JWT_SECRET,
      { expiresIn: '24h' }
    );

    console.log('生成的token信息:', {
      id: admin.id,
      role: admin.role,
      phone: admin.phone
    });

    res.json({
      success: true,
      data: {
        token,
        admin: {
          id: admin.id,
          name: admin.name,
          role: admin.role,
          phone: admin.phone
        }
      }
    });

  } catch (error) {
    console.error('管理员登录失败:', error);
    res.status(500).json({ message: '登录失败' });
    }
};

module.exports = {
    getAllCarousels,
    createNewCarousel,
    modifyCarousel,
    removeCarousel,
    getHotStoresList,
    addNewHotStore,
    modifyHotStore,
    deleteHotStore,
    getUsersStats,
    getCouponsStats,
    getGasStationsStats,
    getAdminInfo,
    getStoresList,
    getStoreDetail,
    auditStore,
    getCouponsList,
    createCoupon,
    updateCouponStatus,
    getStatistics,
    logout,
    sendVerificationCode,
    verifyCode,
    login
};